// src/utils/redisClient.js
import { createClient } from 'redis';
import config from '../config/config.js';

let redisClient;

async function getRedisClient() {
    if (!redisClient) {
        // Redis 连接配置优化
        redisClient = createClient({
            url: `redis://${config.redis.host}:${config.redis.port}`,
            password: config.redis.password,
            socket: {
                reconnectStrategy: (retries) => Math.min(retries * 50, 2000), // 自动重连策略
                timeout: 10000, // 设置超时时间（毫秒）
                keepAlive: 10000 // 保持长时间连接
            }
        });

        redisClient.on('error', (err) => {
            console.error('Redis Client Error:', err);
        });

        // 连接 Redis
        try {
            await redisClient.connect();
            console.log('Redis connected successfully');
        } catch (error) {
            console.error('Failed to connect to Redis:', error);
            redisClient = null; // 连接失败，重置客户端
        }
    }

    return redisClient;
}

export default getRedisClient;